//
//  EFAAboutUsVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/17.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAAboutUsVC.h"
#import "EFAMoreInfoTCell.h"
#import <UIImageView+WebCache.h>
#import "EFASettingVC.h"
#import "EFAWebViewVC.h"
#import "EFAFeedbackVC.h"
#import "GlobalHeader.h"
#import "EFAMoreSetTCell.h"
#import "EFAModel.h"
#import "ApiManager.h"

@interface EFAAboutUsVC ()<UITableViewDelegate, UITableViewDataSource,EFAMoreSetTCellDelegate>

@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (weak,   nonatomic) IBOutlet UIImageView *hPortraitImgView;
@property (weak, nonatomic) IBOutlet UIButton *logoutBtn;
@property (strong, nonatomic) NSArray<NSArray<NSString *> *> *dataArray;
@property (assign, nonatomic) int state;

@end

static NSString *const kReuseCellId = @"EFAMoreInfoTCell";
static NSString *const kReuseCellId2 = @"EFAMoreSetTCell";

@implementation EFAAboutUsVC
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"关于我们";
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    self.view.backgroundColor = ColorFromRGB(0xEDEEF0);
    self.logoutBtn.layer.cornerRadius = 22;
    self.hPortraitImgView.layer.masksToBounds = YES;
    self.hPortraitImgView.layer.cornerRadius = 32.5;
    self.hPortraitImgView.image = [UIImage imageNamed:EFAGlobalImageAppIcon];
    
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    UINib *nib2 = [UINib nibWithNibName:kReuseCellId2 bundle:nil];
    
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    [self.tableView registerNib:nib2 forCellReuseIdentifier:kReuseCellId2];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.tableHeaderView = self.headerBgView;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.logoutBtn.layer.masksToBounds = YES;
    self.logoutBtn.layer.cornerRadius = 22;
    [self.logoutBtn addTarget:self action:@selector(logoutBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)logoutBtnTapped:(UIButton *)btn {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定退出登录？" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"退出登录" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [[NSNotificationCenter defaultCenter] postNotificationName:EFAGlobalNotiLogout object:nil];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section < self.dataArray.count) {
        return self.dataArray[section].count;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    if (indexPath.section < self.dataArray.count) {
        NSArray *titleArray = self.dataArray[indexPath.section];
        if(indexPath.section == 0 || indexPath.section == 1 || indexPath.section == 4){
              EFAMoreInfoTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
            if (indexPath.row < titleArray.count) {
               
                if([titleArray[indexPath.row] isEqualToString:@"应用名"]){
                    cell.leftTitleLabel.text = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
                    cell.rightTitleLabel.text =[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
                    cell.rightArrowImgView.hidden = YES;
                }else{
                    cell.leftTitleLabel.text = titleArray[indexPath.row];
                    cell.rightTitleLabel.hidden = YES;
                }
                cell.portraitImgView.hidden = YES;
            }
            return cell;
        }else{
            EFAMoreSetTCell *cell =[tableView dequeueReusableCellWithIdentifier:kReuseCellId2 forIndexPath:indexPath];
             if (indexPath.row < titleArray.count) {
                 cell.leftTitleLabel.text = titleArray[indexPath.row];
                 cell.rightDetailLabel.hidden =YES;
                 if ([titleArray[indexPath.row]isEqualToString:@"设备新消息提醒"]) {
                       [cell.uiswitch setOn:_tuisongIsNotice];
                 }else if([titleArray[indexPath.row]isEqualToString:@"短信通知"]) {
                       [cell.uiswitch setOn:_smsIsNotice];
                 }else if([titleArray[indexPath.row]isEqualToString:@"电话语音通知"]) {
                       [cell.uiswitch setOn:_phoneIsNotice];
                 }
             }
            cell.delegate = self;
            return cell;
        }
    }
    return nil;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 8.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44.0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section < self.dataArray.count) {
        NSArray *titleArray = self.dataArray[indexPath.section];
        if (indexPath.row < titleArray.count) {
            NSString *title = titleArray[indexPath.row];
            if ([title isEqualToString:@"欢迎页"]) {
                [self jumpToWelcome];
            } else if ([title isEqualToString:@"功能特性"]) {
                [self jumpToFunProperty];
            } else if ([title isEqualToString:@"视频简介"]) {
                [self jumpToVideoIntroduce];
            } else if ([title isEqualToString:@"服务条款"]) {
                [self jumpToServiceProtocol];
            } else if ([title isEqualToString:@"敬告用户"]) {
                [self jumpToNoticeUser];
            } else if ([title isEqualToString:@"用户反馈"]) {
                [self jumpToFeedBack];
            }
        }
    }
}

#pragma mark - EFAMoreSetTCellDelegate
- (void)moreSetTCell:(EFAMoreSetTCell *)cell uiSwitchChanged:(UISwitch *)uiSwitch {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.section < self.dataArray.count) {
       NSArray *titleArray = self.dataArray[indexPath.section];
        NSDictionary *parmas;
        if ([titleArray[indexPath.row]isEqualToString:@"设备新消息提醒"]) {
            NSLog(@"设备新消息提醒");
            _state = 0;
            if (uiSwitch.isOn) {
                parmas = @{@"efairyuserconfig_is_app": @"1"};
                NSLog(@"设备新消息提醒on");
            } else {
                parmas = @{@"efairyuserconfig_is_app":@"0"};
                  NSLog(@"设备新消息提醒off");
            }
        }else if([titleArray[indexPath.row]isEqualToString:@"短信通知"]) {
             NSLog(@"短信通知");
            _state = 1;
            if (uiSwitch.isOn) {
                parmas = @{@"efairyuserconfig_is_sms":@"1"};
                 NSLog(@"短信通知on");
            } else {
                parmas = @{@"efairyuserconfig_is_sms":@"0"};
                 NSLog(@"短信通知on");
            }
        }else if([titleArray[indexPath.row]isEqualToString:@"电话语音通知"]) {
             NSLog(@"电话语音通知");
            _state = 2;
            if (uiSwitch.isOn) {
                parmas = @{@"efairyuserconfig_is_voice":@"1"};
                 NSLog(@"电话语音通知on");
            } else {
                parmas = @{@"efairyuserconfig_is_voice":@"1"};
                 NSLog(@"电话语音通知on");
            }
        }
        if(parmas != nil){
            [self requestConfigInfo:parmas];
        }
    }
}


#pragma mark - event response
#pragma mark - private methods
- (void)jumpToWelcome {
    UIStoryboard *mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UIViewController *loginNavC = [mainSb instantiateViewControllerWithIdentifier:@"EFAWelcomPVC"];
    [self presentViewController:loginNavC animated:YES completion:nil];
}
- (void)jumpToFunProperty {
    EFAWebViewVC *vc = [[EFAWebViewVC alloc] init];
    vc.titleStr = @"功能特性";
    vc.requestUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:EFAGlobalFileAppFunction ofType:@"docx"]];;
    [self showViewController:vc sender:nil];
}
- (void)jumpToVideoIntroduce {
    EFAWebViewVC *vc = [[EFAWebViewVC alloc] init];
    vc.titleStr = @"视频简介";
    vc.requestUrl = [NSURL URLWithString:EFAGlobalIntroduceVideoUrl];
    [self showViewController:vc sender:nil];
}
- (void)jumpToServiceProtocol {
    EFAWebViewVC *vc = [[EFAWebViewVC alloc] init];
    vc.titleStr = @"服务条款";
    vc.requestUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:EFAGlobalFileAppTermServer ofType:@"docx"]];;
    [self showViewController:vc sender:nil];
}
- (void)jumpToNoticeUser {
    EFAWebViewVC *vc = [[EFAWebViewVC alloc] init];
    vc.titleStr = @"敬告用户";
    vc.requestUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"敬告用户" ofType:@"docx"]];
    [self showViewController:vc sender:nil];
}
- (void)jumpToFeedBack {
    EFAFeedbackVC *vc = [[EFAFeedbackVC alloc] init];
    [self showViewController:vc sender:nil];
}



#pragma mark - network request
- (void)requestConfigInfo:(NSDictionary *)configInfo{
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyuser_config_info":configInfo
                           };
    
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiUserConfig] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求用户信息返回：%@", responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求用户信息失败：%@", error);
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}






#pragma mark - network request
#pragma mark - getters and setters
- (NSArray *)dataArray {
    if (!_dataArray) {
        _dataArray = @[@[@"欢迎页", @"功能特性", @"视频简介"],
                       @[@"服务条款", @"敬告用户", @"用户反馈"],
                       @[@"设备新消息提醒"],
                       @[@"短信通知",@"电话语音通知"],
                       @[@"应用名"],
                       ];
    }
    return _dataArray;
}

@end
